package com.mima.minaserver.server;

import java.util.Calendar;
import java.util.Date;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mima.minaserver.repository.OnOffLogRepository;
import com.mima.minaserver.service.IotServerMessage;
import com.mima.minaserver.service.MessageSender;
import com.mima.minaserver.utils.ParameterUtils;

import net.sf.ehcache.CacheManager;

@Service
public class IOTServerHandler extends IoHandlerAdapter {

	private static Logger logger = LoggerFactory.getLogger(IOTServerHandler.class);

	@Autowired
	private IotServerMessage iotServerMessage;
	
	@Autowired
    CacheManager cacheManager;
	
	@Autowired
    MessageSender messageSender;
	
	@Autowired
	ParameterUtils parameterUtils;
	
	@Autowired
	OnOffLogRepository onOffLogRepository;

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		logger.info("Receive---{message:" + message + "}");
		ThreadPoolManager.getInstance(parameterUtils.getPool_size()).getExecutorService().execute(new IOTServerHandlerThread(iotServerMessage, session, message, cacheManager, messageSender, parameterUtils, onOffLogRepository));
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.error("捕获到错了，原因是：" + cause.getMessage(), cause);
	}

	public static void getDate(String time) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(1970, 0, 1, 0, 0, 0);
		Long dec_num = Long.parseLong(time, 16) * 1000;
		calendar.setTimeInMillis(calendar.getTimeInMillis() + dec_num);
	}

	public static Date BytesToDate(byte[] bytes) {
		String dateTimeString = bytesToHexString(bytes);
		StringBuilder stringBuilder = new StringBuilder();
		dateTimeString = dateTimeString.substring(0,8);
		for(int i=0;i<dateTimeString.length()/2;i++) {
			stringBuilder.append(dateTimeString.substring(dateTimeString.length()-((i+1)*2), dateTimeString.length()-(i*2)));
		}
		Calendar calendar = Calendar.getInstance();
		calendar.set(1970, 0, 1, 0, 0, 0);
		Long dec_num = Long.parseLong(stringBuilder.toString(), 16) * 1000;
		calendar.setTimeInMillis(calendar.getTimeInMillis() + dec_num);
		return calendar.getTime();
	}

	public static String bytesToHexString(byte[] bytes) {
		StringBuilder buf = new StringBuilder(bytes.length * 2);
		for (byte b : bytes) { // 使用String的format方法进行转换
			buf.append(String.format("%02x", new Integer(b & 0xff)));
		}
		return buf.toString();
	}

	public static byte[] HexStringtoBytes(String str) {
		if (str == null || str.trim().equals("")) {
			return new byte[0];
		}

		byte[] bytes = new byte[str.length() / 2];
		for (int i = 0; i < str.length() / 2; i++) {
			String subStr = str.substring(i * 2, i * 2 + 2);
			bytes[i] = (byte) Integer.parseInt(subStr, 16);
		}

		return bytes;
	}
	
	public static byte[] intToBytes(int value) {  
        byte[] des = new byte[1];  
        des[0] = (byte) (value & 0xff);  // 低位(右边)的8个bit位  
        return des;  
    }  
	
	 public static int bytesToInt(byte[] des, int offset) {  
	        int value;  
	        value = (int) (des[offset] & 0xff);
	        return value;  
	    }  
}
